#include "head.h"

// Helper function to remove the last directory from a path
int changedir(char* path,char* args, int net_fd, MYSQL* mysql,char* user_id) {
    // 准备SQL查询，确保精确匹配文件名
    char full_path[1024]={0};
    snprintf(full_path,sizeof(full_path),"%s/%s",path,args);
    char sql_buf[1024] = "SELECT path FROM file WHERE path = ? and user_id = ? and `delete` = 0 and `file_type` = 0";
    // 设置预处理的 SQL
    MYSQL_STMT *stmt = mysql_stmt_init(mysql);
    if (!stmt) {
        printf("MySQL Statement Init Failed\n");
        return -1;
    }

    if (mysql_stmt_prepare(stmt, sql_buf, strlen(sql_buf)) != 0) {
        printf("MySQL Statement Prepare Failed: %s\n", mysql_stmt_error(stmt));
        mysql_stmt_close(stmt);
        return -1;
    }

    // 放入参数
    MYSQL_BIND bind[2];
    memset(bind, 0, sizeof(bind));
    bind[0].buffer_type = MYSQL_TYPE_STRING;
    bind[0].buffer = (char *)full_path;
    bind[0].buffer_length = strlen(full_path); // 不需要包含结束符
   
    bind[1].buffer_type = MYSQL_TYPE_STRING;
    bind[1].buffer = (char *)user_id;
    bind[1].buffer_length = strlen(user_id); // 不需要包含结束符
    mysql_stmt_bind_param(stmt, bind);

    // 执行查询
    if (mysql_stmt_execute(stmt) != 0) {
        printf("MySQL Statement Execute Failed: %s\n", mysql_stmt_error(stmt));
        mysql_stmt_close(stmt);
        return -1;
    }

    // 绑定结果集
    MYSQL_BIND bind_result;
    char result_column[60];
    memset(&bind_result, 0, sizeof(bind_result));
    bind_result.buffer_type = MYSQL_TYPE_STRING;
    bind_result.buffer = result_column;
    bind_result.buffer_length = sizeof(result_column);
    mysql_stmt_bind_result(stmt, &bind_result);

    // 获取查询结果
    int fetch_num = mysql_stmt_fetch(stmt);
    if (fetch_num != 0) {
        const char* msg = "没有找到对应的路径";
        send(net_fd, msg, strlen(msg), 0);
    } else {
        // 查询到的路径
        char buf[4096] = {0};
        snprintf(buf, sizeof(buf), "%s", result_column);
        send(net_fd, buf, strlen(buf), 0);
    }

    mysql_stmt_close(stmt);
    return 0;
}



